from flask import Blueprint,jsonify,request
from db import db1
from utils.rs import rs
import json

bp_work = Blueprint('work',__name__)


@bp_work.route('/worklist')
def worklist():
    sql = "select * from workflow"
    res = db1.find_all(sql)
    return jsonify({'code':200,'list':res})


# 获取数据源接口
@bp_work.route('/getresourcedata',methods=['POST','GET'])
def getresourcedata():
    if request.method == 'GET':
        # 从redis取,如果有直接返回
            values = rs.get_str('dataresouce')
            if values:
                list = eval(values)
            else:
                # 如果没有查询
                sql = "select * from data_source"
                res = db1.find_all(sql)
                list = []
                if res:
                    list = eval(values)
                    for i in res:
                        dict={'id':i['id'],'name':i['name']}
                        sql1 = "select id,name,type from %s"%(i['tablename'])
                        subres = db1.find_all(sql1)
                        dict['mes'] = subres
                        list.append(dict)
                #存入redis
                rs.set_str('dataresouce',json.dumps(list))
            return jsonify({"code":200,'list':list})
    else:
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = "update workflow set params='%s' where id=%d"%(data['mes'],int(data['id']))
        print(sql)
        db1.update(sql)
        res = db1.find_all(sql)
        return jsonify({"code":200})

        
@bp_work.route('/getworkf')
def getworkf():
    id = request.args.get('id')
    sql = "select * from workflow where id=%d"%(int(id))
    res = db1.find(sql)
    return jsonify({'code':200,'workf':res})